﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc; 
using Microsoft.AspNetCore.Authorization;
using WebApplication3.Data;
using DotNetCore.CAP;
using WebApplication3.Models;
using WebApplication3.Data.Entities;
using WebApplication3.Helpers;
using System.IO;
using System.Net;
using System.Text;

namespace WebApplication3.Controllers
{
	[Authorize ]
	public class CourierController : Controller
	{
		private readonly ApplicationDbContext _applicationDbContext;
		private readonly ICapPublisher _capPublisher;

		public CourierController(ApplicationDbContext applicationDbContext, ICapPublisher  capPublisher)
		{
			this._applicationDbContext = applicationDbContext;
			this._capPublisher = capPublisher;
		}
        public IActionResult Index()
        {
			var orders = _applicationDbContext.OrderEntities.Where(s=>s.Status==0);

			var re = new Models.OrderViewModel {

				OrderDetails = orders.Select(s=>
				new Models.OrderDetailViewModel {
					Id	=s.Id, ProductName=s.ProductName,

					 ReceiveAddress=s.ReceiveAddress,
					  ReceiveMobile=s.ReceiveMobile,
					   ReceiveName=s.ReceiveName,
					    WeightGram=s.WeightGram
				  

				}) .ToList() 
			};

			return View(re);
        }

		public IActionResult ActionOrder(int id) {
			var order = this._applicationDbContext.OrderEntities.SingleOrDefault(s => s.Id == id);

			order.Status = 1;//接单状态
			this._applicationDbContext.SaveChanges();
			_capPublisher.Publish("Courier/ActionOrder", order);
			//using (var trans = _applicationDbContext.Database.BeginTransaction(_capPublisher, autoCommit: true))
			//{
				
				 
			//}
			return Ok(id); 
		}
		[CapSubscribe("Courier/ActionOrder1")]
		public void CheckReceivedMessage1(DateTime datetime)
		{
			Console.WriteLine(datetime);
		}
		[CapSubscribe("Courier/ActionOrder")]
		public async Task CheckReceivedMessageAsync(OrderEntity  orderEntity)
		{
			var postData = new Models.SFCreateOrderModel();

			postData.receive = new Models.ReceiveModel()
			{
				user_address = orderEntity.ReceiveAddress,
				user_lng = "116.362175",//orderEntity.ReceiveLongitude,//116.362175,40.022113
				user_lat = "40.022113",//orderEntity.ReceiveLatitude,
				user_name = orderEntity.ReceiveName,
				user_phone = orderEntity.ReceiveMobile
				 
			};

			var customer = _applicationDbContext.Users.SingleOrDefault(s=>s.OpenId==orderEntity.OpenId);
			postData.shop = new Models.ShopModel
			{
				shop_address = "广西市场同城揽收",
				shop_name = customer.CNName+","+customer.ShopNo,
				shop_phone = customer.Mobile,
				shop_lng = orderEntity.CustomerLongitude, //114.071214,22.643877
				shop_lat = orderEntity.CustomerLatitude
			};

			postData.order_detail = new Models.OrderDetailModel
			{
				total_price = 10,
				product_type = 99,
				weight_gram = orderEntity.WeightGram,
				product_num = 1,
				product_type_num = 1,
				 
				ProductDetails = new List<Models.ProductDetailModel> {

					 new Models.ProductDetailModel{
						  product_name=orderEntity.ProductName,
						   product_num=1,    
					 } 
					 }
			};
			 //postData.push_time = DateTime.Now.ConvertDateTimeToInt();
			 postData.shop_order_id = orderEntity.Id+"";
			var json = postData.SerializeObject();


			var signChar = string.Format("{0}&{1}&{2}", json,
				ConstData.DevId, ConstData.DevKey);

			var md5 = signChar.GetMD5();
			var base64 = md5.GetBase64();

			var sign = signChar.GetMD5().GetBase64();


			var jsonResult =await  HttpHelper.PostUrlAsync(string.Format(ConstData.OrderCreateUrl, sign), json);

			  
			var resultModel = jsonResult.DeserializeObject<SFResultModel >();

			var order = this._applicationDbContext.OrderEntities.SingleOrDefault(s => s.Id == orderEntity.Id);
			if (resultModel.error_code != 0)
			{
				order.Status = 3; 
			}
			else
			{
				var createOrderOkResult = jsonResult.DeserializeObject<SFResultSuccecRootModel>();
				order.Status = 2;//成功

			}

			
			order.StatusData = jsonResult;
		
			order.UpdatedAt = DateTime.Now;
			_applicationDbContext.SaveChanges();
		}


		
	}
}